package org.jeeasy.common.core.config;

import com.alibaba.druid.support.jakarta.WebStatFilter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeeasy.common.core.domain.IAuthUser;
import org.jeeasy.common.core.enums.RestCode;
import org.jeeasy.common.core.exception.JeeasyException;
import org.jeeasy.common.core.service.CurrentAuthUserService;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Druid 管理页面访问配置
 *
 * @author wei.yang
 * @date 2025-01-05
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class DruidManagerConfig {
    private final CurrentAuthUserService currentAuthUserService;

    /**
     * 解决druid 监控页面排序参数报错
     *
     * @return factory
     */
    @Bean
    public TomcatServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addConnectorCustomizers(connector -> {
            connector.setProperty("relaxedPathChars", "\"<>[\\]^`{|}");
            connector.setProperty("relaxedQueryChars", "\"<>[\\]^`{|}");
        });
        return factory;
    }

    /**
     * 注册DruidFilter拦截
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean<CusDruidFilter> duridFilterRegistrationBean() {
        FilterRegistrationBean<CusDruidFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new CusDruidFilter(currentAuthUserService));
        Map<String, String> initParams = new HashMap<>();
        //设置忽略请求
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico");
        filterRegistrationBean.setInitParameters(initParams);
        filterRegistrationBean.addUrlPatterns("/druid/*");
        return filterRegistrationBean;
    }


    @RequiredArgsConstructor
    public static class CusDruidFilter extends WebStatFilter {
        private final CurrentAuthUserService currentAuthUserService;
        private final static String DRUID_PERMISSION = "sys-monitor-druid";

        /**
         * 过滤druid监控页面的访问权限
         *
         * @param request  请求对象
         * @param response 响应对象
         * @param chain    过滤链
         * @throws IOException      如果发生I/O错误
         * @throws ServletException 如果发生Servlet错误
         */
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            if (Objects.nonNull(currentAuthUserService)) {
                IAuthUser currentAuthUser = currentAuthUserService.getCurrentAuthUser(request);
                var permissionSet = currentAuthUser.getPermissionSet();
                boolean b = permissionSet.stream().anyMatch(DRUID_PERMISSION::equals);
                if (b) {
                    super.doFilter(request, response, chain);
                } else {
                    throw new JeeasyException(RestCode.NO_AUTH);
                }
            }
        }
    }
}
